package com.sunlee.admin.api.module.job.task;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunlee.admin.api.module.oss.cloud.OssFactory;
import com.sunlee.admin.api.module.oss.entity.SysOssEntity;
import com.sunlee.admin.api.module.oss.service.SysOssService;
import com.sunlee.admin.api.constant.StringConstant;
import com.sunlee.admin.api.module.job.dto.AutoImportPptTaskDTO;
import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.utils.EnvUtil;
import com.sunlee.common.core.utils.StringUtil;
import com.sunlee.common.service.entity.ProductEntity;
import com.sunlee.common.service.entity.ThirdProductEntity;
import com.sunlee.common.service.enums.StatusEnum;
import com.sunlee.common.service.enums.ThirdResStatusEnum;
import com.sunlee.common.service.service.*;
import io.github.artislong.model.OssInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author sunulee
 */
@Component("autoImportPptTask")
public class AutoImportPptTask implements ITask {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 防止重复执行
     */
    private static boolean isRun = false;

    @Autowired
    private ProductService productService;

    @Autowired
    private SysOssService sysOssService;

    @Autowired
    private ProductCategoryMappingService productCategoryMappingService;


    @Autowired
    private ThirdProductService thirdProductService;

    @Autowired
    private ThirdProductCategoryMappingService thirdProductCategoryMappingService;

    @Autowired
    private ThirdCategoryMappingService thirdCategoryMappingService;

    @Override
    public void run(String params) {
        if (EnvUtil.isPro()) {
            return;
        }

        logger.info("autoImportPptTask定时任务正在执行，参数为：{}", params);

        AutoImportPptTaskDTO dto = validaDTO(params);

        if (isRun) {
            logger.info("autoImportPptTask定时任务不可重复执行");
            return;
        }

        isRun = true;
        try {
            start(dto);
        } finally {
            isRun = false;
        }
    }

    private void start(AutoImportPptTaskDTO dto) {


        // 查询指定或所有需要入库的PPT
        List<ThirdProductEntity> fileInfoList = thirdProductService.list(new LambdaQueryWrapper<ThirdProductEntity>()
                // 指定第三方文件来源
                .eq(ThirdProductEntity::getSource, dto.getSource())
                // 指定第三方资源ID
                .in(CollectionUtils.isNotEmpty(dto.getThirdResId()), ThirdProductEntity::getThirdResId, dto.getThirdResId())
                // 只处理状态为PPT已解析的，如果指定第三方资源ID则不限制
                .eq(CollectionUtils.isEmpty(dto.getThirdResId()), ThirdProductEntity::getStatus, ThirdResStatusEnum.RESOLVED.getCode())
                // 限制数量，如果指定第三方资源ID或者未设置则不限制
                .last(CollectionUtils.isEmpty(dto.getThirdResId()) && Objects.nonNull(dto.getTotal()), "LIMIT " + dto.getTotal()));

        int listSize = fileInfoList.size();
        logger.info("=====待新增资源总数[{}]", listSize);

        if (CollectionUtils.isEmpty(fileInfoList)) {
            return;
        }

        for (ThirdProductEntity fileInfo : fileInfoList) {
            try {
                handleThirdProduct(fileInfo);
            } catch (Exception e) {
                logger.error("PPT发布处理异常:thirdId={},generateDir{},", fileInfo.getThirdResId(), fileInfo.getGenerateDir(), e);
                fileInfo.setStatus(ThirdResStatusEnum.ERROR.getCode());
                fileInfo.setStatusMsg(StringUtil.subString("PPT发布处理异常：" + e.getMessage(), 0, 2000));
            } finally {
                thirdProductService.updateById(fileInfo);
            }
            productCategoryMappingService.autoMappingProductCategoryByProductId(fileInfo.getResId());
        }
        logger.info("autoImportPptTask定时任务执行结束，总数[{}]条]", fileInfoList.size());
    }


    private void handleThirdProduct(ThirdProductEntity fileInfo) {

        ProductEntity productEntity = null;
        if (Objects.nonNull(fileInfo.getResId())) {
            // 存在
            productEntity = productService.getById(fileInfo.getResId());
        }

        if (Objects.isNull(productEntity)) {
            // 不存在则插入商品表
            productEntity = convert(fileInfo);
            boolean prodSaveRes = productService.insertOwn(productEntity);

            if (!prodSaveRes) {
                throw new BusinessException("插入商品表返回失败");
            }
            fileInfo.setResId(productEntity.getId());
        }

        // 成功修改第三方资源表的资源状态
        fileInfo.setStatus(ThirdResStatusEnum.COMPLETED.getCode());
        fileInfo.setStatusMsg("");
    }


    /**
     * 第三方资源实体 to 己方资源实体
     *
     * @param fileInfo 第三方资源实体
     * @return 己方资源实体
     */
    private ProductEntity convert(ThirdProductEntity fileInfo) {
        ProductEntity productEntity = new ProductEntity();

        productEntity.setTitle(fileInfo.getTitle());
        productEntity.setSalesPrice(0.0D);
        productEntity.setOriginalPrice(0.0D);
        // 默认有效
        productEntity.setStatus(StatusEnum.VALID.getCode());
        productEntity.setShortDesc(fileInfo.getContent());
        productEntity.setTag(fileInfo.getTag());
        productEntity.setMissFont(fileInfo.getMissFont());

        String generateDir = com.sunlee.admin.api.util.FileUtil.appendSeparator(fileInfo.getGenerateDir()) + fileInfo.getTitle();
        // 首图
        productEntity.setIcon(uploadFile(generateDir + StringConstant.FIRST_JPG));
        // 多图
        productEntity.setMultiImg(uploadFile(generateDir + StringConstant.NINE_JPG));
        // 全图
        productEntity.setAllImg(uploadFile(generateDir + StringConstant.ALL_JPG));
        // 富文本
        productEntity.setRichText(MessageFormat.format(StringConstant.RICH_TEXT_CONTENT, productEntity.getAllImg()));
        // 资源下载路径
        productEntity.setDownloadUrl(uploadFile(generateDir + StringConstant.ZIP));

        return productEntity;
    }


    public String uploadFile(String filePath) {

        // 校验文件是否存在
        File file = new File(filePath);
        if (!file.isFile()) {
            throw new BusinessException("不存在该文件：" + filePath);
        }

        String type = FileUtil.getType(file);
        String name = FileUtil.getPrefix(filePath);

        String uploadPath = com.sunlee.admin.api.util.FileUtil.getPathByDate(name, type);

        //上传文件
        OssInfo ossInfo = OssFactory.client().upLoad(FileUtil.getInputStream(file), uploadPath);

        //记录上传文件
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setName(name);
        ossEntity.setFileType(type);
        ossEntity.setUrl(ossInfo.getPath() + Constant.SYMBOL_SLASH + ossInfo.getName());
        ossEntity.setCreateDate(new Date());
        ossEntity.setType(OssFactory.client().getConfig().getType());
        sysOssService.insertOwn(ossEntity);
        return ossEntity.getUrl();
    }

    private AutoImportPptTaskDTO validaDTO(String params) {
        AutoImportPptTaskDTO dto = validaParseParam(params, AutoImportPptTaskDTO.class);
        if (Objects.isNull(dto.getSource()) || dto.getSource() < 0) {
            throw new BusinessException(ErrorCodeEnum.PARAM_NOT_COMPLETE);
        }
        return dto;
    }
}
